package com.cx.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.cx.pojo.Order;
import com.cx.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Controller
public class alipay {
    @Autowired
    OrderService orderService;
    private boolean isSuccess =false;
    private Order orderInfo = new Order();//存储订单信息
    private final String APP_ID = "2016102900775671";
    private final String APP_PRIVATE_KEY = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCGyc+pi+d8yMYJwojtxek3Yk+2lYsEHREynqo4Hfaags57KnxnAHQdHZx7D1w4mhcgtbkAZFR9uvx4Fpy06pUgIHJ+Lvr1Es0To8glotOyEeVKUM2DOE0GyYiqGmqXktED2cXSRTmzivuwPbYv0Stp+YdmUKsLEGJxKaXB2sRflkIgHPYbE0wjKosDkAcsqle03CERMVS9dy5t0dvIhh6vKFfA7bxKsYPRemNT5XOLp8co9Wob+negImX9ojDcZm5qYmTXsiosIJ1CBocsB3fgj2iXHSytiGfUntDpMuRTYxfoQJCfn/2HNwvk0RzQa7kBdOqqMbuuRsfJhLeS4fx7AgMBAAECggEAD1txEKVDE8GgZr5GcajqAIhwAqKZOzfAnN7dEBXB4irjMb9Oe0He+O5FxPOkE0LjPbPWx0enJMgoOdqBsk9D/GwV/3CE4WVp/kHb7QXXTuOhF02LjNbeV9agfpkR6gEtVV37nxCKGX3NXXA6kMopQyLOHYc1ZcZRIQmYvDSbyTQgHvetcxYY0OAY8mbd1GDE3waubg2hBNKsfHc+o2p3hp2XBil3PjEVjrcU2mTmIpaBNdD3vceG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WqDGbufRqKerumepHvKDcY2bQICDq48rbxfrwMnR+vKXSdC4sq256K/HhhXb4+hJGWSKeiU0RFVtTQgxLolW0Vbwn09TfSGzOryW5y7HOgnzCqgjVPx6XhUEFE4enF/UZB6HhMSv2b6l/vmX3GW5i5kQcxSkO8N07Pp/dArXH+FGIDNk8rSV2xGlAMAdrE7FlKx5tIkE4X06GNy+AqTSHycmxsBSdAPrgDppQhviJ5u6/Dv8J4Bzf4Ljvb4XC3p8CtqQxWvvnA+PBLcrn/l67JyF3EPMDe/OqpnANXn6lUU6nWRkKxVQUQjvGKa1wK2CSkGixWMRetQIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://vrqiak.natappfree.cc/notifyUrl";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://vrqiak.natappfree.cc/returnUrl";

    @RequestMapping("generotorOrderInfo")//获取前端传递过来的订单信息：比如下单人名称,下单的金额，下单的时间，下单的酒店名称，下单的房间类型，入住，离店时间
    public String generotorOrderInfo(){
//        orderInfo.setUserId(1);
//        orderInfo.setHotelName("上海证大美爵酒店");
//        orderInfo.setRoomType("总统套房");
//        orderInfo.setOrderStatus(1888);
//        orderInfo.setMoveInDate("2020/6/18");
//        orderInfo.setMoveOutDate("2020/6/22");
//        orderInfo.setOrderDate("2020/6/14");
        return "redirect:/alipay";
    }
    public String test(){
        return "forward:hello.html";
    }
    @RequestMapping("alipay")
    public void alipay(HttpServletResponse httpResponse) throws IOException {
//        orderInfo.setUserId(1);
//        orderInfo.setHotelName("上海证大美爵酒店");
//        orderInfo.setRoomType("总统套房");
//        orderInfo.setOrderStatus(1888);
//        orderInfo.setMoveInDate("2020/6/18");
//        orderInfo.setMoveOutDate("2020/6/22");
//        orderInfo.setOrderDate("2020/6/14");
        System.out.println(1);
        Random r=new Random();
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        String out_trade_no = UUID.randomUUID().toString();
        //付款金额，必填
        String total_amount =Integer.toString(orderInfo.getOrderStatus());
        //订单名称，必填
        String subject =orderInfo.getHotelName() + orderInfo.getRoomType();
        //商品描述，可空
        String body = "尊敬的会员欢迎入住"+orderInfo.getHotelName() +"的"+ orderInfo.getRoomType();
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
        System.out.println(3);
    }

    /**
     * 这个是付款完毕后等待5秒后跳转的页面，所以需要让notify处理器先持久化数据库，这个在返回页面
     * @param request
     * @param response
     * @return
     * @throws IOException
     * @throws AlipayApiException
     */
    @RequestMapping(value = "/returnUrl", method = RequestMethod.GET)
    public String returnUrl(HttpServletRequest request, HttpServletResponse response)
            throws IOException, AlipayApiException {
        System.out.println("=================================同步回调=====================================");

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY,CHARSET,SIGN_TYPE); // 调用SDK验证签名
        System.out.println(signVerified);
        //验证签名通过
        if(signVerified){
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            System.out.println("商户订单号="+out_trade_no);
            System.out.println("支付宝交易号="+trade_no);
            System.out.println("付款金额="+total_amount);

            //支付成功，修复支付状态
            orderInfo.setOther1("0");//支付成功设置值为0
//            payService.updateById(Integer.valueOf(out_trade_no));
            return "forward:success.html";//跳转付款成功页面
        }else{
            orderInfo.setOther1("1");//支付失败设置值为1
            return "forward:no.html";//跳转付款失败页面
        }
    }
    @RequestMapping("/notifyUrl")
    @ResponseBody
    /**
     * 这个方法是付款完毕立即处理的逻辑
     */
    public String getNOTIFY_URL(){
        orderService.insert(orderInfo);
        isSuccess = true;
        System.out.println(111);
        return "完成notify";
    }

}


